<template>
    <view>
        <j-cell-group>
            <j-cell-card title="通道" :tips="channel + 1" :show="false" :is-touch="false" border style="background: #f5f7fb">
                <template v-for="(item, index) in StorageSnapshotList">
                    <j-cell :key="index" title="1" :more="false" @jftap="bindtapChannel(index)">
                        <view slot="tips" v-if="index === channel">
                            <uni-icons custom-prefix="iconfont" type="icon-duihao" size="24" color="#FF0025"></uni-icons>
                        </view>
                    </j-cell>
                </template>
            </j-cell-card>

            <j-cell title="冗余" :more="false">
                <view slot="tips">
                    <switch :checked="StorageSnapshotList[channel].Redundancy" @change="bindchangeRedundancy"></switch>
                </view>
            </j-cell>

            <j-cell title="预拍" :more="false">
                <view slot="tips" style="display: flex; align-items: center">
                    <input :value="StorageSnapshotList[channel].PreSnap" type="number" class="input-control" @input="bindinputPreRecord" />
                    <text style="padding: 0 20rpx">张</text>
                </view>
            </j-cell>

            <j-cell-card title="抓拍模式" :show="false" :is-touch="false" border style="background: #f5f7fb">
                <j-cell title="配置" :more="false" @jftap="bindtapRecordMode('ConfigSnap')">
                    <view slot="tips" v-if="StorageSnapshotList[channel].SnapMode === 'ConfigSnap'">
                        <uni-icons custom-prefix="iconfont" type="icon-duihao" size="24" color="#FF0025"></uni-icons>
                    </view>
                </j-cell>
                <j-cell title="始终" :more="false" @jftap="bindtapRecordMode('ManualSnap')">
                    <view slot="tips" v-if="StorageSnapshotList[channel].SnapMode === 'ManualSnap'">
                        <uni-icons custom-prefix="iconfont" type="icon-duihao" size="24" color="#FF0025"></uni-icons>
                    </view>
                </j-cell>
                <j-cell title="关闭" :more="false" @jftap="bindtapRecordMode('ClosedSnap')">
                    <view slot="tips" v-if="StorageSnapshotList[channel].SnapMode === 'ClosedSnap'">
                        <uni-icons custom-prefix="iconfont" type="icon-duihao" size="24" color="#FF0025"></uni-icons>
                    </view>
                </j-cell>
            </j-cell-card>

            <j-cell-card
                title="录像工作表"
                :show="false"
                :is-touch="false"
                border
                style="background: #f5f7fb; padding-bottom: 140rpx"
                v-if="StorageSnapshotList[channel].SnapMode === 'ConfigSnap'"
            >
                <view style="border-bottom: 1px solid #eeeeee">
                    <picker :value="week" :range="weeks" @change="bindchangeWeeks">
                        <view style="display: flex; justify-content: space-between; align-items: center; background: #ffffff; padding: 20rpx">
                            <view>星期</view>
                            <view>{{ weeks[week] }}</view>
                        </view>
                    </picker>
                </view>
                <view style="border-bottom: 1px solid #eeeeee" v-for="(item, index) in timeMaskList" :key="index">
                    <picker mode="multiSelector" :value="item.time" :range="[hours, minutes, hours, minutes]" @change="bindchangeTime($event,index)">
                        <view style="display: flex; justify-content: space-between; align-items: center; background: #ffffff; padding: 20rpx">
                            <view>时间段{{ index + 1 }}</view>
                            <view>{{ hours[item.time[0]] }}:{{ minutes[item.time[1]] }} -- {{ hours[item.time[2]] }}:{{ minutes[item.time[3]] }}</view>
                        </view>
                    </picker>

                    <checkbox-group @change="bindchangeMask($event, index)" style="display: flex; justify-content: space-around; align-items: center; padding: 20rpx 0">
                        <label>
                            <checkbox value="1" :checked="item.mask[0] === 1" />
                            普通
                        </label>
                        <label>
                            <checkbox value="2" :checked="item.mask[1] === 1" />
                            检测
                        </label>
                        <label>
                            <checkbox value="3" :checked="item.mask[2] === 1" />
                            报警
                        </label>
                    </checkbox-group>
                </view>
            </j-cell-card>
        </j-cell-group>

        <view class="bottom-fixed">
            <button type="primary" class="block" plain @tap="bindtapSave">保存</button>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            token: '',
            StorageSnapshotList: [],
            channel: 0,
            weeks: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '全部'],
            week: 0,
            hours: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24'],
            minutes: [
                '00',
                '01',
                '02',
                '03',
                '04',
                '05',
                '06',
                '07',
                '08',
                '09',
                '10',
                '11',
                '12',
                '13',
                '14',
                '15',
                '16',
                '17',
                '18',
                '19',
                '20',
                '21',
                '22',
                '23',
                '24',
                '25',
                '26',
                '27',
                '28',
                '29',
                '30',
                '31',
                '32',
                '33',
                '34',
                '35',
                '36',
                '37',
                '38',
                '39',
                '40',
                '41',
                '42',
                '43',
                '44',
                '45',
                '46',
                '47',
                '48',
                '49',
                '50',
                '51',
                '52',
                '53',
                '54',
                '55',
                '56',
                '57',
                '58',
                '59'
            ],
            timeMaskList: []
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        this.token = options.token
        this.week = new Date().getDay()
        this.getconfig();
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    methods: {
        getconfig() {
            uni.showLoading();
            let token = this.token;
            let data = {
                Name: 'Storage.Snapshot'
            };
            getApp().globalData.api.getconfig(data, token, (result) => {
                uni.hideLoading({
                    success: (res) => {
                        console.log(result);
						this.StorageSnapshotList = result['Storage.Snapshot']
						if (this.week <= 6) {
						    this.TimeSectionMaskTo(this.week);
						} else {
						    for (let i = 0; i < 7; i++) {
						        this.TimeSectionMaskTo(i);
						    }
						}
                    }
                });
            });
        },

        // 通道
        bindtapChannel(ev) {
            this.channel = Number(ev);
            this.getconfig();
        },

        // 冗余
        bindchangeRedundancy(ev) {
            this.StorageSnapshotList[this.channel].Redundancy = ev.detail.value;
        },

        // 预拍
        bindinputPreRecord(ev) {
            this.StorageSnapshotList[this.channel].PreSnap = Number(ev.detail.value);
        },

        // 配置模式
        bindtapRecordMode(ev) {
            this.StorageSnapshotList[this.channel].SnapMode = ev
        },

        // 星期
        bindchangeWeeks(ev) {
			this.week = Number(ev.detail.value)
			this.TimeSectionMaskTo(this.week);
        },

        // 时间段
        bindchangeTime(ev, index) {
            console.log(ev, this.timeMaskList);
            // let index = index;
            let value = ev.detail.value;

            for (let i = 0; i < this.timeMaskList.length; i++) {
                const item = this.timeMaskList[i];

                if (i === index) {
                    item.time = value;
                    break;
                }
            }

            if (this.week <= 6) {
                this.ToTimeSectionMask(this.week);
            } else {
                for (let i = 0; i < 7; i++) {
                    this.ToTimeSectionMask(i);
                }
            }
        },

        // mask
        bindchangeMask(ev, index) {
            console.log(ev, this.timeMaskList);
            // let index = index;
            let value = ev.detail.value;
            let maskArray = [1, 1, 1];

            if (value.length <= 0) {
                maskArray = [0, 0, 0];
            } else {
                if (!value.includes('1')) {
                    maskArray[0] = 0;
                }

                if (!value.includes('2')) {
                    maskArray[1] = 0;
                }

                if (!value.includes('3')) {
                    maskArray[2] = 0;
                }
            }

            for (let i = 0; i < this.timeMaskList.length; i++) {
                const item = this.timeMaskList[i];

                if (i === index) {
                    item.mask = maskArray;
                    break;
                }
            }

            if (this.week <= 6) {
                this.ToTimeSectionMask(this.week);
            } else {
                for (let i = 0; i < 7; i++) {
                    this.ToTimeSectionMask(i);
                }
            }
        },

        /** ================================================ TimeSection 和 Mask 的转换 ===================================================== */
        // 传参转本地
        TimeSectionMaskTo(week) {
            let record = this.StorageSnapshotList[this.channel]; // 获取某通道数据

            let timeSectionList = record.TimeSection; // TimeSection集合

            let maskList = record.Mask; // Mask集合

            let timeSectionArray = timeSectionList[week]; // 星期几的TimeSection（6个时间段）

            let maskArray = maskList[week]; // 星期几的Mask（6个时间段对应的mask选项）

            let timeMaskList = [];
            timeSectionArray.forEach((item, index) => {
                maskArray.forEach((pro, size) => {
                    if (index === size) {
                        let timeArray = this.TimeSectionTo(item);
                        let maskArray = this.MaskTo(pro);
                        timeMaskList.push({
                            time: timeArray,
                            mask: maskArray
                        });
                    }
                });
            });
            this.timeMaskList = timeMaskList
        },

        // 本地转传参
        ToTimeSectionMask(week) {
            let maskArray = [];
            let timeArray = [];
            this.timeMaskList.forEach((item, index) => {
                maskArray.push(this.ToMask(item.mask));

                if (index === 0) {
                    timeArray.push('1 ' + this.ToTimeSection(item.time));
                } else {
                    timeArray.push('0 ' + this.ToTimeSection(item.time));
                }
            });
            this.StorageSnapshotList[this.channel].Mask[week] = maskArray;
            this.StorageSnapshotList[this.channel].TimeSection[week] = timeArray;
        },

        // 返回的时间格式转换为本地时间格式
        TimeSectionTo(str) {
            let arr1 = str.split(' ');
            let prefix = arr1[0];
            let suffix = arr1[1];
            let arr2 = suffix.split('-');
            let start = arr2[0];
            let end = arr2[1];
            let arr3 = start.split(':');
            let startHour = arr3[0];
            let startMinute = arr3[1];
            let startSecond = arr3[2];
            let arr4 = end.split(':');
            let endHour = arr4[0];
            let endMinute = arr4[1];
            let endSecond = arr4[2];
            let timeArray = [];

            for (let i = 0; i < this.hours.length; i++) {
                const item = this.hours[i];

                if (item === startHour) {
                    timeArray.push(i);
                }
            }

            for (let i = 0; i < this.minutes.length; i++) {
                const item = this.minutes[i];

                if (item === startMinute) {
                    timeArray.push(i);
                }
            }

            for (let i = 0; i < this.hours.length; i++) {
                const item = this.hours[i];

                if (item === endHour) {
                    timeArray.push(i);
                }
            }

            for (let i = 0; i < this.minutes.length; i++) {
                const item = this.minutes[i];

                if (item === endMinute) {
                    timeArray.push(i);
                }
            }

            return timeArray;
        },

        // 本地时间格式转换为参数需要的时间格式
        ToTimeSection(timeArray) {
            let str = '';
            let startHour = this.hours[timeArray[0]];
            let startMinute = this.minutes[timeArray[1]];
            let endHour = this.hours[timeArray[2]];
            let endMinute = this.minutes[timeArray[3]];
            str = startHour + ':' + startMinute + ':00-' + endHour + ':' + endMinute + ':00';
            return str;
        },

        // 返回的Mask格式转换为本地Mask格式
        MaskTo(str) {
            let maskArray = [];

            if (str === '0x00000007') {
                maskArray = [1, 1, 1];
            } else if (str === '0x00000006') {
                maskArray = [0, 1, 1];
            } else if (str === '0x00000005') {
                maskArray = [1, 1, 0];
            } else if (str === '0x00000004') {
                maskArray = [0, 1, 0];
            } else if (str === '0x00000003') {
                maskArray = [1, 0, 1];
            } else if (str === '0x00000002') {
                maskArray = [0, 0, 1];
            } else if (str === '0x00000001') {
                maskArray = [1, 0, 0];
            } else if (str === '0x00000000') {
                maskArray = [0, 0, 0];
            }

            return maskArray;
        },

        // 本地的mask格式转换为参数需要的Mask
        ToMask(maskArray) {
            let str = '';

            if (JSON.stringify(maskArray) === '[1,1,1]') {
                str = '0x00000007';
            } else if (JSON.stringify(maskArray) === '[0,1,1]') {
                str = '0x00000006';
            } else if (JSON.stringify(maskArray) === '[1,1,0]') {
                str = '0x00000005';
            } else if (JSON.stringify(maskArray) === '[0,1,0]') {
                str = '0x00000004';
            } else if (JSON.stringify(maskArray) === '[1,0,1]') {
                str = '0x00000003';
            } else if (JSON.stringify(maskArray) === '[0,0,1]') {
                str = '0x00000002';
            } else if (JSON.stringify(maskArray) === '[1,0,0]') {
                str = '0x00000001';
            } else if (JSON.stringify(maskArray) === '[0,0,0]') {
                str = '0x00000000';
            }

            return str;
        },

        bindtapSave(ev) {
            this.setconfig();
        },

        // 设置配置
        setconfig() {
            uni.showLoading();
            let token = this.token;
            let data = {
                Name: 'Storage.Snapshot',
                'Storage.Snapshot': this.StorageSnapshotList
            };
            getApp().globalData.api.setconfig(data, token, (result) => {
                uni.showToast({
                    title: '保存成功'
                });
            });
        }
    }
};
</script>
<style></style>
